package com.zxl.manager.utils;

import org.apache.log4j.Logger;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * Created by jimmy on 2017/8/12.
 */
public class CryptUtil {

    private static Logger logger = Logger.getLogger(CryptUtil.class);

    public static String MD5(String str){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            return bytesToHex(md5.digest(str.getBytes("utf-8")));
        }catch (Exception e){
            logger.error("MD5加密异常",e);
            return null;
        }
    }

    /**
     * 二进制转十六进制
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        // 把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toLowerCase();
    }
}
